#ifndef __FIFO_FPP__
#define __FIFO_FPP__

#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <cstdlib>
#include <fcntl.h>
#include <cassert>

using namespace std;
#define Mode 0666
#define Path "fifo"
class Fifo
{
public:
    Fifo(string path = Path) : _path(path)
    {
        umask(0);
        //创建管道
        int n = mkfifo(_path.c_str(), Mode);
        if(n == 0)
        {
            cout << "fifo create success" <<endl;
        }
        else 
        {
            cout << "fifo fail, errno: " << errno << " stringerrno: " << strerror(errno) << endl;
        }
    }
    ~Fifo()
    {
        //删除管道，管道也是文件
        int n = unlink(_path.c_str());
        if(n == 0)
        {
            cout << "fifo remove success" <<endl;
        }
        else 
        {
            cout << "fifo remove, errno: " << errno << " stringerrno: " << strerror(errno) << endl;
        }
    }

private:
    string _path;//文件名+文件路径
};

class Sync
{
public:
    Sync() :wfd(-1), rfd(-1)
    {}

    void OpenWrite()
    {
        wfd = open(Path, O_WRONLY);
        if(wfd < 0)
        {
            cout << "writeopen fail" <<endl;
            exit(1);
        }
    }

    void OpenRead()
    {
        rfd = open(Path, O_RDONLY);
        if(rfd < 0)
        {
            cout << "readopen fail" <<endl;
            exit(1);
        }
    }

    bool Wait()
    {
        bool ret = true;
        uint32_t c = 0;
        ssize_t n = read(rfd, &c, sizeof(uint32_t));
        if(n == sizeof(uint32_t))
        {
            cout << "等待后，读取数据..." << endl;
        }
        else if(n == 0)
        {
            ret = false;
        }
        else 
        {
            return false;
        }
        return ret;
    }   

    void Wakeup()
    {
        uint32_t c = 0;
        ssize_t n = write(wfd, &c, sizeof(uint32_t));
        assert(n == sizeof(uint32_t));
        cout << "唤醒..." << endl;
    }

    ~Sync()
    {}

private:
    int wfd;
    int rfd;
};

#endif
